<template>
  <div class="relation-device">
    <DynamicForm ref="dynamicFormRef" @click="callBack" :rulesForm="state.rulesForm" :refresh="state.refresh"/>
    <DynamicDialog ref="dynamicDialogRef" @click="callBack" :dialogVisible="state.visible"
                   :button="{cancel:false,confirm:false}"
                   title="选择设备">
      <template #dialog>
        <SearchTable ref="searchTableRef" v-if="state.visible" @click="callBack" :deviceType="state.deviceType"
                     :rulesForm="state.rulesForm" :rules="state.rules" width="500px"/>
      </template>
    </DynamicDialog>
  </div>
</template>

<script lang="ts" setup>
import {ref, onMounted, reactive, defineEmits, defineProps} from 'vue';

import DynamicForm from '@/components/layout/form/dynamic-form.vue';
import DynamicDialog from '@/components/layout/dialog/dynamic-dialog.vue';
import SearchTable from '@/views/monitor/device/search/Index';
import {relationForms} from '@/assets/script/monitor/forms/room/device-relation-form';
import {ElMessage} from 'element-plus';


import type {DevicePublicRelation} from '@/model/DevicePublicRelation';
import {deletePublicApi, insertDeviceRelationApi, listDeviceRelationApi} from "@/api/device";

const dynamicFormRef = ref(DynamicForm)
const dynamicDialogRef = ref(DynamicDialog)
const searchTableRef = ref(SearchTable)
const relation = relationForms

const props = defineProps({
  row: {} as any
})
const emits = defineEmits<{ (e: 'click', data: object): void }>()

const state = reactive({
  rulesForm: [] as any,
  refresh: null as any,
  visible: false,
  deviceType: null as any,
  data: {} as any,
  row: {} as any,
  device: [] as any
})

onMounted(() => {
  state.rulesForm = relationForms
  // 去掉默认值
  let card = state.rulesForm[0].card
  card.forEach((e: any) => {
    e[e.name] = null
  })
  state.refresh = Math.random()
  state.row = props.row
  listDeviceRelation()
})

const callBack = (data: any) => {
  switch (data.type || '') {
    case 'dialogClose':
      state.visible = false
      break
    case 'search':
      state.deviceType = data.data
      state.visible = true
      break
    case 'choice':
      // eslint-disable-next-line no-case-declarations
      let card = state.rulesForm[0].card.find((f: any) => f.searchKey === data.value)
      card[card.name] = data.data.deviceCode
      state.data[card.name] = data.data
      state.refresh = Math.random()
      state.visible = false
      break
    case 'submit':
      // eslint-disable-next-line no-case-declarations
      let devicePublicRelation: DevicePublicRelation[] = []
      // eslint-disable-next-line no-case-declarations
      let category: any, storey: any, storeyName: any,
          floor: any, floorName: any, room: any, roomName: any;
      if (state.row.dictionaryCode === 'floor') {
        category = 2
        storey = state.row.parentCode
        storeyName = '-'
        floor = state.row.constCode
        floorName = state.row.constName
      } else if (state.row.dictionaryCode === 'room') {
        category = 3
        floor = state.row.parentCode
        floorName = '-'
        room = state.row.constCode
        roomName = state.row.constName
      } else {
        category = 1
        storey = state.row.constCode
        storeyName = state.row.constName
      }
      for (let v in data.data) {
        let item = state.data[v]
        if (!item) {
          continue
        }
        devicePublicRelation.push({
          deviceId: item.id,
          deviceName: item.deviceName,
          deviceCode: item.deviceCode,
          deviceType: item.constCode,
          category: category,
          storey: storey,
          storeyName: storeyName,
          floor: floor,
          floorName: floorName,
          room: room,
          roomName: roomName
        })
      }
      if (devicePublicRelation.length > 0) {
        insertDeviceRelationApi(devicePublicRelation).then((data: any) => {
          if (data.code === 0) {
            ElMessage.success('保存成功！')
            emits('click', {type: 'dialogClose', data: true})
          } else {
            ElMessage.success('保存失败！')
          }
        })
      } else {
        deletePublicApi({
          category: category,
          storey: storey,
          storeyName: storeyName,
          floor: floor,
          floorName: floorName,
          room: room,
          roomName: roomName
        }).then(() => {
          ElMessage.success('保存成功！')
          emits('click', {type: 'dialogClose', data: true})
        })
      }
      console.log('callBack', devicePublicRelation)
      break
    default:
      console.log('callBack', data)
      break
  }
}
const listDeviceRelation = () => {
  let params = {}
  switch (state.row.dictionaryCode || '') {
    case 'floor':
      params['floor'] = state.row.constCode
      break
    case 'room':
      params['room'] = state.row.constCode
      break
    default:
      params['storey'] = state.row.constCode
      break
  }
  listDeviceRelationApi(params).then((data: any) => {
    state.device = data
    // 去掉默认值
    let card = state.rulesForm[0].card
    card.forEach((e: any) => {
      let item = data.find((f: any) => f.deviceType === e.name)
      if (item) {
        state.data[e.name] = {
          constCode: item.deviceType,
          deviceName: item.deviceName,
          deviceCode: item.deviceCode,
          id: item.deviceId
        }
        e[e.name] = item.deviceCode
      }
    })
    console.log('state.rulesForm', state.rulesForm)
    state.refresh = Math.random()
  })
}
</script>